package baiqitun.dynamictable.config;

import baiqitun.dynamictable.core.MyDynamicTableNameInterceptor;
import baiqitun.dynamictable.core.MyTableNameHandler;
import baiqitun.dynamictable.entity.SysStudent;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.util.HashMap;

/**
 * MyBatis Plus 配置
 * @author kedaji
 */


@Import(cn.hutool.extra.spring.SpringUtil.class)
@MapperScan("baiqitun.dynamictable.mapper")
@Slf4j
@Configuration
public class MybatisPlusConfig {
    @Autowired
    private SpringUtil springUtil;


    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        // 取消MyBatis Plus的最大分页500条的限制
        paginationInnerInterceptor.setMaxLimit(100000L);
        MyDynamicTableNameInterceptor myDynamicTableNameInterceptor = new MyDynamicTableNameInterceptor();
        HashMap<String, MyTableNameHandler> map = new HashMap<String, MyTableNameHandler>(2) {{
            //整个函数返回的结果就是替换后的新表名，这个生成的表名的规则可以自己随便指定
            put("test_student", (sql, tableName, student) -> tableName + "_" +((SysStudent)student).getDepartCode());
        }};

        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        myDynamicTableNameInterceptor.setTableNameHandlerMap(map);
        interceptor.addInnerInterceptor(myDynamicTableNameInterceptor);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);

        return interceptor;
    }
}
